﻿using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Authentication;
using ZGLXM.Domain;
using ZGLXM.ErrorCode;
using ZGLXM.Infra.Interface;
using ZGLXM.Infra.Repository;
using ZGLXM.Writh.Api.Applicantion.Command.RBAC;

namespace ZGLXM.Writh.Api.Applicantion.Handler.RBAC
{
    public class UserDeleteCommandHandler : IRequestHandler<UserDeleteCommand, ApiResult>
    {
        private readonly IUserRepository userRepository;
        private readonly IMapper mapper;
        private readonly ILogger<UserDeleteCommandHandler> logger;

        public UserDeleteCommandHandler(IUserRepository userRepository, IMapper mapper, ILogger<UserDeleteCommandHandler> logger)
        {
            this.userRepository = userRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult> Handle(UserDeleteCommand request, CancellationToken cancellationToken)
        {
            var user = await userRepository.GetAsync(x => x.UserId == request.UserId);
            if (user == null)
            {
                return ApiResult.Fail("用户不存在");
            }
            user.IsDeleted = true;
            user = mapper.Map<User>(user);
            var result = await userRepository.UpdateAsync(user);
            if (result > 0)
            {
                return ApiResult.OK("删除成功");
            }
            else
            {
                return ApiResult.Fail("删除失败");
            }
        }
    }
}
